//
//  HomeVC.m
//  SSWiFi
//
//  Created by 酷安 @啥也不会啊啊啊啊啊啊  on 2024/1/23.
//

#import "HomeVC.h"
#import "HomeWCApi.h"
#import "HomeJDYApi.h"
#import "Api.h"
#import "HomeCollectionViewCell.h"
#import "MoreViewController.h"
#import "Utils.h"
#import "LoginSettingVC.h"


@interface HomeVC ()<UICollectionViewDelegate,UICollectionViewDataSource,HomeCollectionViewCellDelegate>
@property (strong,nonatomic) UICollectionView* collectionView;
//@property (strong,nonatomic) HomeBaseApi *homeApi;
@property (strong,nonatomic) NSTimer *timer;
@property(nonatomic, strong) NSMutableArray *dataSource;

//@property (strong,nonatomic) NSArray *loginIps;
//@property (strong,nonatomic) NSArray *loginPaths;
//@property (strong,nonatomic) NSMutableArray *successLogins;
@property (strong,nonatomic) UILabel *lb_tip;
@end

@implementation HomeVC
static NSString * const reuser_homeCollectionViewCell = @"HomeCollectionViewCell";
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor qd_backgroundColor];
    self.title = @"随身WiFi";
    self.navigationItem.rightBarButtonItem = [UIBarButtonItem qmui_itemWithTitle:@"更多" target:self action:@selector(moreClick)];
//    self.successLogins = [NSMutableArray array];
    [self setUp];
    [QMUITips showLoading:@"自动登录中.." inView:self.view];
    [self autoLogin];
    
}


- (void)autoLogin{
    [Utils testLoginIp:[UserConfig loginIps] loginPaths:[UserConfig serverPaths] CallBack:^(NSArray * _Nonnull successArr) {
        [QMUITips hideAllTips];
        if(successArr.count > 0){
            NSDictionary *serverinfo = [successArr lastObject];
            [self login:serverinfo];
        }else{
            [self refreshData];
        }
    }];
}

- (void)login:(NSDictionary *)serverinfo{
    Api *api = [[Api alloc] init:serverinfo];
    [UserConfig shareInstance].api = api;
    [api loginCallback:^(bool flag) {
        [self timeStart];
    }];
}

- (void)refresh_lbtipMsg{
    
    NSString *tip = [NSString stringWithFormat:@"未登录 v%@ 酷安 @啥也不会啊啊啊啊啊啊",[Utils appVersion]];
    if([UserConfig shareInstance].isLogin){
        NSDictionary *serverinfo = [UserConfig shareInstance].api.serverinfo;
        NSString *ip = [serverinfo objectForKey:@"ip"];
        NSString *pwd = [serverinfo objectForKey:@"pwd"];
        tip = [NSString stringWithFormat:@"v%@ %@:%@",[Utils appVersion],ip,pwd];
    }
    self.lb_tip.text = tip;
}

- (void)timeStart{
    [QMUITips hideAllTips];
    [self refreshData];
    MJWeakSelf
//    [self.timer invalidate];
//    self.timer = nil;
    if(self.timer == nil){
        self.timer = [NSTimer timerWithTimeInterval:2 repeats:YES block:^(NSTimer * _Nonnull timer) {
            NSLog(@"timer:%@",timer);
            [weakSelf refreshData];
        }];
        [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSDefaultRunLoopMode];
    }
}



- (void)moreClick{
    MoreViewController  *vc = [[MoreViewController alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}

//- (void)autoLogin:(NSArray *)devicesApi idx:(NSInteger)idx{
//    if(idx >= devicesApi.count){
//        [self reloadData];
//        [QMUITips hideAllToastInView:self.view animated:YES];
//        return;
//    }
//    HomeBaseApi *api = devicesApi[idx];
//    if([UserConfig shareInstance].isLogin){
//        [QMUIConsole log:[NSString stringWithFormat:@"使用%@登录成功",api.devicesName]];
//        [QMUITips hideAllToastInView:self.view animated:YES];
//        return;
//    }
//    [QMUIConsole log:[NSString stringWithFormat:@"正在尝试使用%@登录",api.devicesName]];
//    MJWeakSelf
//    [api loginCallback:^(bool flag, NSString * _Nonnull msg) {
//       if(flag){
//           [UserConfig shareInstance].api = api;
//           [QMUIConsole log:[NSString stringWithFormat:@"使用%@登录成功",api.devicesName]];
//           [weakSelf login_Ok];
//       }else{
//           [weakSelf autoLogin:devicesApi idx:idx+1];
//       }
//    }];
//}






//- (void)login_Ok{
//    [QMUITips hideAllTips];
//    [self refreshData];
//    MJWeakSelf
////    self.timer = [NSTimer timerWithTimeInterval:1 repeats:YES block:^(NSTimer * _Nonnull timer) {
////        [weakSelf refreshData];
////    }];
////    self.view.backgroundColor = [UIColor qd_backgroundColor];
////    [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSDefaultRunLoopMode];
//
//
//}

- (void)setUp{
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    self.collectionView.bounces = NO;
    self.collectionView.showsHorizontalScrollIndicator = NO;
    self.collectionView.pagingEnabled = NO;
    [self.collectionView registerNib:[UINib nibWithNibName:@"HomeCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:reuser_homeCollectionViewCell];

    self.collectionView.contentInset = UIEdgeInsetsMake(10, 10, 10, 10);
    [self refresh_lbtipMsg];
}

//- (void)addNotification{
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loginChange:) name:Noti_loginChange object:nil];
//
//}

- (void)loginChange:(id)values{
//    self.time
    NSLog(@"%@",values);
    
}

- (void)removeNotification{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)dealloc{
    [self removeNotification];
}

- (void)refreshData{
    MJWeakSelf;
    if([UserConfig shareInstance].isLogin){
        [[UserConfig shareInstance].api getHomeDataCallback:^(NSArray<HomeItemModel *> * _Nonnull data) {
            [weakSelf.dataSource removeAllObjects];
            [weakSelf.dataSource addObjectsFromArray:data];
            [weakSelf reloadData];
        } errorBack:^(NSError * _Nonnull err) {
            NSLog(@"%@",err);
            [weakSelf.dataSource removeAllObjects];
            [self reloadData];
        }];
    }else{
        if(!self.emptyView.isHidden){
            [self reloadData];
        }
        [self.timer invalidate];
        self.timer = nil;
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self autoLogin];
         });
    }
    [self refresh_lbtipMsg];
}

- (void)reloadData{
    
    if(self.dataSource.count == 0){
        NSMutableArray *ips = [NSMutableArray array];
        for(NSDictionary *d in [UserConfig loginIps]){
            [ips addObject:[NSString stringWithFormat:@"ip:%@ 密码:%@",d[@"ip"],d[@"pwd"]]];
        }
        NSString *msg = [ips componentsJoinedByString:@"\n"];
        if(msg.length > 0){
            msg = [NSString stringWithFormat:@"已尝试\n%@",msg];
        }
        [self showEmptyViewWithText:@"自动登录失败" detailText:msg buttonTitle:@"设置登录接口" buttonAction: @selector(loginSettingClick)];
        [self.collectionView setHidden:YES];
    }else{
        [self hideEmptyView];
        [self.collectionView setHidden:NO];
    }
    [self.collectionView reloadData];
}

- (void)loginSettingClick{
    LoginSettingVC *vc =[[LoginSettingVC alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}

+ (instancetype)defaultVC{
    return [[self alloc] init];;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.dataSource.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{

    // 从缓存池里取
    // UICollectionViewCell 没有UIImageView
    HomeCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:reuser_homeCollectionViewCell forIndexPath:indexPath];
    cell.model = self.dataSource[indexPath.row];
    cell.celldelegate = self;
    return cell;
}


#pragma mark - HomeCollectionViewCellDelegate

- (void)value1Click:(NSString *)value{
    [[UIPasteboard generalPasteboard] setString:value];
    [QMUITips showWithText:[NSString stringWithFormat:@"%@ 已复制",value]];
}

- (void)edit1Click:(HomeItemModel *)model{
    NSLog(@"%@",@(model.type));
    if(model.type == HomeCellType_WiFiInfo){ //修改WiFi名称
        [self editWiFiSSID:model.model];
    }else if (model.type == HomeCellType_WiFiSeting){ //修改WiFi范围
        [self setWiFiCoverage:model.model];
    }else if (model.type == HomeCellType_IMEI){
        [self setIMEI:model.model];
    }
}

- (void)edit2Click:(HomeItemModel *)model{
    if(model.type == HomeCellType_TotalUseByte){ //流量设置
        [self userDataDig:model.model];
    }
}

- (void)editWiFiSSID:(HomeDataModel *)model{
    QMUIDialogTextFieldViewController *dialogViewController = [[QMUIDialogTextFieldViewController alloc] init];
    dialogViewController.title = @"修改WiFi信息";
    [dialogViewController addTextFieldWithTitle:@"WiFi名称" configurationHandler:^(QMUILabel *titleLabel, QMUITextField *textField, CALayer *separatorLayer) {
        textField.placeholder = @"WiFi名称(不超过22个字符)";
        textField.maximumTextLength = 22;
        textField.text = model.SSID1;
    }];
    [dialogViewController addTextFieldWithTitle:@"WiFi密码" configurationHandler:^(QMUILabel *titleLabel, QMUITextField *textField, CALayer *separatorLayer) {
        textField.placeholder = @"WiFi密码";
        textField.maximumTextLength = 30;
//        textField.secureTextEntry = YES;
        textField.text = [model get_ssid_pwd];
    }];
    dialogViewController.enablesSubmitButtonAutomatically = NO;// 为了演示效果与第二个 cell 的区分开，这里手动置为 NO，平时的默认值为 YES
    [dialogViewController addCancelButtonWithText:@"取消" block:nil];
    [dialogViewController addSubmitButtonWithText:@"确定" block:^(QMUIDialogTextFieldViewController *aDialogViewController) {
        NSString *sid = [aDialogViewController.textFields.firstObject.text qmui_trim];
        NSString *pwd = [aDialogViewController.textFields.lastObject.text qmui_trim];
        if (sid.length == 0 || pwd.length == 0) {
            [QMUITips showInfo:@"请填写内容" inView:aDialogViewController.view];
            return;
        }
        if(pwd.length < 8){
            [QMUITips showInfo:@"密码至少8位" inView:aDialogViewController.view];
            return;
        }
        [aDialogViewController hide];
        if(![sid isEqualToString:model.SSID1] || ![pwd isEqualToString:model.get_ssid_pwd]){
            [self submitWiFiInfoWithSsid:sid pwd:pwd];
        }
        NSLog(@"%@  %@", sid,pwd);
    }];
    [dialogViewController show];
}

- (void)setWiFiCoverage:(HomeDataModel *)model{
    QMUIDialogSelectionViewController *dialogViewController = [[QMUIDialogSelectionViewController alloc] init];
    dialogViewController.title = @"WiFi覆盖范围";
    NSArray *dt = @[
    @{
        @"name" : @"short_mode",
        @"value": @"短距离(省电)"
    },
   @{
       @"name" : @"medium_mode",
       @"value": @"中距离"
   },
   @{
       @"name" : @"long_mode",
       @"value": @"远距离"
   },];
    
    dialogViewController.items = [dt valueForKey:@"value"];
    [dialogViewController setSelectedItemIndex: [[dt valueForKey:@"name"] indexOfObject:model.wifi_coverage]];
    [dialogViewController addCancelButtonWithText:@"取消" block:nil];
    MJWeakSelf;
    [dialogViewController addSubmitButtonWithText:@"确定" block:^(QMUIDialogViewController *aDialogViewController) {
        QMUIDialogSelectionViewController *d = (QMUIDialogSelectionViewController *)aDialogViewController;
        if (d.selectedItemIndex == QMUIDialogSelectionViewControllerSelectedItemIndexNone) {
            [QMUITips showError:@"请至少选一个" inView:d.qmui_modalPresentationViewController.view hideAfterDelay:1.2];
            return;
        }
        NSString *selectname = [dt[d.selectedItemIndex] objectForKey:@"name"];;
        [aDialogViewController hideWithAnimated:YES completion:^(BOOL finished) {
            [weakSelf submitWiFiCover:selectname orgName:model.wifi_coverage];
        }];
    }];
    [dialogViewController show];
}

- (void)submitWiFiCover:(NSString *)name orgName:(NSString *)orgName{
    if(![name isEqualToString:orgName]){
        [[UserConfig shareInstance].api setWiFiCoveragePara:name callback:^(bool flag) {
            [self.navigationController popToRootViewControllerAnimated:YES];
        }];
    }
}






- (void)submitWiFiInfoWithSsid:(NSString *)ssid pwd:(NSString *)pwd{
    [QMUITips showLoadingInView:self.view];
    [[UserConfig shareInstance].api setWiFiInfoWithSsid:ssid pwd:pwd callback:^(bool flag) {
        [QMUITips hideAllTips];
    }];
}

- (void)userDataDig:(HomeDataModel *)model{
    MJWeakSelf;
    QMUIDialogTextFieldViewController *dialogViewController = [[QMUIDialogTextFieldViewController alloc] init];
    dialogViewController.title = @"设置流量套餐(GB)";
    [dialogViewController addTextFieldWithTitle:@"已使用" configurationHandler:^(QMUILabel *titleLabel, QMUITextField *textField, CALayer *separatorLayer) {
        textField.placeholder = @"请输入已使用的流量(GB)";
        textField.keyboardType = UIKeyboardTypeDecimalPad;
        NSInteger month_total = model.monthly_rx_bytes.integerValue + model.monthly_tx_bytes.integerValue;
        textField.text =[NSString bytesToG:month_total appendunit:NO];
    }];
    [dialogViewController addTextFieldWithTitle:@"总流量" configurationHandler:^(QMUILabel *titleLabel, QMUITextField *textField, CALayer *separatorLayer) {
        textField.placeholder = @"请输入套餐总流量(GB)";
        textField.maximumTextLength = 10;
        textField.keyboardType = UIKeyboardTypeNumberPad;
        textField.text = [NSString stringWithFormat:@"%@",@([model.data_volume_limit_size integerValue])];
    }];
    dialogViewController.enablesSubmitButtonAutomatically = NO;// 为了演示效果与第二个 cell 的区分开，这里手动置为 NO，平时的默认值为 YES
    [dialogViewController addCancelButtonWithText:@"取消" block:nil];
    [dialogViewController addSubmitButtonWithText:@"确定" block:^(QMUIDialogTextFieldViewController *aDialogViewController) {
        double usedata = [[aDialogViewController.textFields.firstObject.text qmui_trim] doubleValue] * 1024;
        NSInteger totaldata = [[aDialogViewController.textFields.lastObject.text qmui_trim] integerValue];
        [aDialogViewController hide];
        [weakSelf submitUseData:usedata totalData:totaldata];
//        NSLog(@"%@  %@", sid,pwd);
    }];
    [dialogViewController show];
}

- (void)submitUseData:(double)usedata totalData:(NSInteger)totalData{
    [QMUITips showLoadingInView:self.view];
    
    dispatch_queue_t concurrentQueue = dispatch_queue_create("com.example.concurrentQueue", DISPATCH_QUEUE_CONCURRENT);
    // 创建一个dispatch_group
    
    dispatch_group_t apiGroup = dispatch_group_create();
    dispatch_group_enter(apiGroup);
    __block bool a = FALSE;
    [[UserConfig shareInstance].api setUserDataNum:totalData callback:^(bool flag) {
        a = flag;
        NSLog(@"a");
        dispatch_group_leave(apiGroup);
        
    }];
    __block bool b = FALSE;
    dispatch_group_enter(apiGroup);
    [[UserConfig shareInstance].api setUsedata:usedata callback:^(bool flag, NSString * _Nonnull msg) {
        b = flag;
        NSLog(@"b");
        dispatch_group_leave(apiGroup);
    }];
    dispatch_group_notify(apiGroup, concurrentQueue, ^{
        dispatch_async(dispatch_get_main_queue(), ^{
            [QMUITips hideAllTips];
                    if(a && b){
                        [QMUITips showSucceed:@"设置成功"];
                    }
        });
    });
}

- (void)setIMEI:(HomeDataModel *)model{
    MJWeakSelf;
    [Utils alertTextDig:@"修改串号" placehold:@"请输入15位串号" text:model.imei keyboardType:UIKeyboardTypeNumberPad enablesSubmitButtonAutomatically:YES block:^(NSString *value, QMUIDialogViewController *aDialogViewController) {
        if(value.length != 15){
            [QMUITips showError:@"请输入15位串号" inView:aDialogViewController.view];
        }else{
            [aDialogViewController hide];
            if([model.imei isEqual:value]){
                return;
            }
            [weakSelf alertIMEIWarming:model newImei:value];
        }
    }];
}

- (void)alertIMEIWarming:(HomeDataModel *)model newImei:(NSString *)newImei{
    QMUIAlertAction *action1 = [QMUIAlertAction actionWithTitle:@"取消" style:QMUIAlertActionStyleCancel handler:nil];
    MJWeakSelf;
    QMUIAlertAction *action2 = [QMUIAlertAction actionWithTitle:@"确定" style:QMUIAlertActionStyleDestructive handler:^(__kindof QMUIAlertController * _Nonnull aAlertController, QMUIAlertAction * _Nonnull action) {
        [weakSelf submitChangeIMEI:newImei];
    }];
    NSString *msg = [NSString stringWithFormat:@"串号:%@ -> %@ \n变更后请手动重启设备后查看IMEI是否修改成功\n操作不当可能会导致锁卡,请谨慎操作",model.imei,newImei];
    QMUIAlertController *alertController = [QMUIAlertController alertControllerWithTitle:@"确定要变更串号吗?" message:msg preferredStyle:QMUIAlertControllerStyleActionSheet];
    [alertController addAction:action1];
    [alertController addAction:action2];
    [alertController showWithAnimated:YES];
}

-  (void)submitChangeIMEI:(NSString *)newIMEI{
    [QMUITips showLoadingInView:self.view];
    dispatch_group_t apiGroup = dispatch_group_create();
    dispatch_queue_t concurrentQueue = dispatch_queue_create("com.example.concurrentQueue", DISPATCH_QUEUE_CONCURRENT);
    NSMutableArray *successLogins = [NSMutableArray array];
    NSArray *goformIds = @[@"SET_IMEI_NUM",@"ALK_WRITE_IMEI", ];
    
    for(NSString *goformId in goformIds){
        dispatch_group_enter(apiGroup);
        [[UserConfig shareInstance].api setIMEI:newIMEI goformId:goformId callback:^(NSString * _Nonnull msg) {
            NSString *prmsg = [NSString stringWithFormat:@"goformId:%@ newIMEI:%@  msg:%@",goformId, newIMEI,msg];
            NSLog(@"%@",prmsg);
            [successLogins addObject:prmsg];
            dispatch_group_leave(apiGroup);
        }];
    }
    dispatch_group_notify(apiGroup, concurrentQueue, ^{
        dispatch_async(dispatch_get_main_queue(), ^{
            [QMUITips hideAllTips];
//            NSLog(@"%@",successLogins);
            if([[successLogins componentsJoinedByString:@","] containsString:@"success"]){
                [QMUITips showSucceed:@"更改成功,重启中..."];
                [self reboot];
            }else{
                [QMUITips showError:@"更改失败"];
            }
        });
    });
    
    
    
//    [[UserConfig shareInstance].api setIMEI:newIMEI callback:^(NSString * _Nonnull msg) {
//        [QMUITips hideAllTips];
////        [QMUITips showWithText:msg];
//        [self reboot];
////        if([msg isEqualToString:@"success"]){
////
////        }else{
////            [QMUITips showWithText:@"请重启设备查看是否修改成功"];
////        }
//    }];
}

- (void)reboot{
//    [QMUITips showLoading:@"自动重启中" inView:self.view];
    [[UserConfig shareInstance].api rebootCallback:^(bool flag, NSString * _Nonnull msg) {
        [QMUITips hideAllTips];
        [QMUITips showWithText:@"如设备重启失败,请手动重启后查看IMEI是否修改成功"];
    }];
}

- (UICollectionView *)collectionView{
    if(!_collectionView){
        // 创建一个流水布局
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        // 行间距
        layout.minimumLineSpacing = 10;
        // 设置cell之间的间距
        layout.minimumInteritemSpacing = 10;
         // 设置cell的尺寸
        layout.itemSize = CGSizeMake((ScreenBoundsSize.width - layout.minimumLineSpacing-20) / 2, 130);

         // 设置滚动的方向
         layout.scrollDirection = UICollectionViewScrollDirectionVertical;
        _collectionView = [[UICollectionView alloc] initWithFrame:[[UIScreen mainScreen] bounds] collectionViewLayout:layout];
        [self.view addSubview:_collectionView];
        _collectionView.backgroundColor = [UIColor clearColor];
        
        [_collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.equalTo(self.view);
        }];
    }
    return _collectionView;
}

- (NSMutableArray *)dataSource{
    if(!_dataSource){
        _dataSource = [[NSMutableArray alloc] init];
    }
    return _dataSource;
}

- (UILabel *)lb_tip{
    if(!_lb_tip){
        _lb_tip = [[UILabel alloc] init];
        _lb_tip.textColor = [UIColor qd_mainTextColor];
        [self.view insertSubview:_lb_tip belowSubview:self.collectionView];
        [_lb_tip setFont:[UIFont systemFontOfSize:14]];
        [_lb_tip mas_makeConstraints:^(MASConstraintMaker *make) {
            make.bottom.equalTo(self.view).offset(-15);
            make.left.equalTo(self.view).offset(20);
        }];
        _lb_tip.text = @"未登录";
    }
    return _lb_tip;
}
@end
